import { 
  DIAGRAM_TYPES, 
  ELEMENT_TYPES, 
  ACTIVITY_TYPES,
  RELATIONSHIP_TYPES,
  VISIBILITY_TYPES,
  STATE_TYPES,
  PARTICIPANT_TYPES,
  USECASE_TYPES,
  MESSAGE_TYPES,
  METHOD_MODIFIERS,
  ATTRIBUTE_MODIFIERS,
  NOTE_POSITIONS
} from './constants.js'
import { 
  getVisibilitySymbol, 
  getDiagramTypeTitle 
} from './utils.js'

/**
 * 生成PlantUML代码
 * @param {Array} elements - 元素数组
 * @param {string} diagramType - 图表类型
 * @param {string} title - 图表标题
 * @returns {string} PlantUML代码
 */
export function generatePlantUMLCode(elements, diagramType, title = '') {
  let code = '@startuml\n'
  
  // 使用用户定义的标题，如果为空则不显示title行
  if (title && title.trim()) {
    code += `title ${title.trim()}\n\n`
  }
  
  // 设置纯白色背景
  code += 'skinparam backgroundColor white\n'
  code += 'skinparam classBackgroundColor white\n'
  code += 'skinparam interfaceBackgroundColor white\n'
  code += 'skinparam enumBackgroundColor white\n'
  code += 'skinparam activityBackgroundColor white\n'
  code += 'skinparam stateBackgroundColor white\n'
  code += 'skinparam usecaseBackgroundColor white\n'
  code += 'skinparam participantBackgroundColor white\n'
  code += 'skinparam actorBackgroundColor white\n\n'

  switch (diagramType) {
    case DIAGRAM_TYPES.CLASS:
      code += generateClassDiagram(elements)
      break
    case DIAGRAM_TYPES.ACTIVITY:
      code += generateActivityDiagram(elements)
      break
    case DIAGRAM_TYPES.SEQUENCE:
      code += generateSequenceDiagram(elements)
      break
    case DIAGRAM_TYPES.USECASE:
      code += generateUseCaseDiagram(elements)
      break
    case DIAGRAM_TYPES.STATE:
      code += generateStateDiagram(elements)
      break
  }

  code += '@enduml'
  return code
}

/**
 * 生成类图代码
 * @param {Array} elements - 元素数组
 * @returns {string} 类图代码
 */
function generateClassDiagram(elements) {
  let code = ''
  
  // 收集包和命名空间
  const packages = elements.filter(el => el.type === ELEMENT_TYPES.PACKAGE)
  const namespaces = elements.filter(el => el.type === ELEMENT_TYPES.NAMESPACE)
  const notes = elements.filter(el => el.type === ELEMENT_TYPES.NOTE)
  
  // 先定义包和命名空间
  packages.forEach(pkg => {
    code += `package "${pkg.name}" {\n`
    // 包内的类将在后面处理
    code += '}\n\n'
  })
  
  namespaces.forEach(ns => {
    code += `namespace ${ns.name} {\n`
    // 命名空间内的类将在后面处理
    code += '}\n\n'
  })
  
  // 定义所有类、接口和枚举
  elements.forEach(element => {
    if (element.type === ELEMENT_TYPES.CLASS) {
      // 处理抽象类
      const isAbstract = element.isAbstract ? 'abstract ' : ''
      
      code += `${isAbstract}class ${element.name}`
      
      // 处理泛型
      if (element.genericType) {
        code += `<${element.genericType}>`
      }
      
      // 处理包含关系
      if (element.packageId) {
        const pkg = packages.find(p => p.id === element.packageId)
        if (pkg) {
          // 不需要额外处理，因为类将被放在包内
        }
      }
      
      code += ' {\n'
      
      // 处理属性
      if (element.attributes && element.attributes.length > 0) {
      element.attributes.forEach(attr => {
          const visibility = getVisibilitySymbol(attr.visibility || VISIBILITY_TYPES.PUBLIC)
          const modifier = attr.modifier ? `{${attr.modifier}} ` : ''
          const type = attr.type ? `: ${attr.type}` : ''
          code += `  ${visibility} ${modifier}${attr.name}${type}\n`
        })
      }
      
      // 处理方法
      if (element.methods && element.methods.length > 0) {
      element.methods.forEach(method => {
          const visibility = getVisibilitySymbol(method.visibility || VISIBILITY_TYPES.PUBLIC)
          const modifier = method.modifier ? `{${method.modifier}} ` : ''
          const params = method.parameters ? `(${method.parameters})` : '()'
          const returnType = method.returnType ? `: ${method.returnType}` : ''
          code += `  ${visibility} ${modifier}${method.name}${params}${returnType}\n`
        })
      }
      
      code += '}\n\n'
    } else if (element.type === ELEMENT_TYPES.INTERFACE) {
      code += `interface ${element.name}`
      
      // 处理泛型
      if (element.genericType) {
        code += `<${element.genericType}>`
      }
      
      code += ' {\n'
      
      // 处理方法
      if (element.methods && element.methods.length > 0) {
      element.methods.forEach(method => {
          const params = method.parameters ? `(${method.parameters})` : '()'
          const returnType = method.returnType ? `: ${method.returnType}` : ''
          code += `  ${method.name}${params}${returnType}\n`
      })
      }
      
      code += '}\n\n'
    } else if (element.type === ELEMENT_TYPES.ENUM) {
      code += `enum ${element.name} {\n`
      
      // 处理枚举值
      if (element.attributes && element.attributes.length > 0) {
      element.attributes.forEach(attr => {
        code += `  ${attr.name}\n`
      })
      }
      
      code += '}\n\n'
    }
  })

  // 处理注释
  notes.forEach(note => {
    if (note.targetId) {
      const target = elements.find(el => el.id === note.targetId)
      if (target) {
        code += `note ${note.position || 'right'} of ${target.name} : ${note.content}\n`
      } else {
        code += `note "${note.content}" as N${note.id}\n`
      }
    } else {
      code += `note "${note.content}" as N${note.id}\n`
    }
  })
  
  code += '\n'

  // 定义关系
  elements.forEach(element => {
    if (element.type === ELEMENT_TYPES.RELATIONSHIP && element.sourceId && element.targetId) {
      const source = elements.find(el => el.id === element.sourceId)
      const target = elements.find(el => el.id === element.targetId)
      
      if (source && target) {
        // 处理关系标签和多重性
        const label = element.name ? ` : ${element.name}` : ''
        const sourceMultiplicity = element.sourceMultiplicity ? ` "${element.sourceMultiplicity}"` : ''
        const targetMultiplicity = element.targetMultiplicity ? ` "${element.targetMultiplicity}"` : ''
        
        switch (element.relationshipType) {
          case RELATIONSHIP_TYPES.INHERITANCE:
            code += `${source.name} <|-- ${target.name}${label}\n`
            break
          case RELATIONSHIP_TYPES.IMPLEMENTATION:
            code += `${source.name} <|.. ${target.name}${label}\n`
            break
          case RELATIONSHIP_TYPES.COMPOSITION:
            code += `${source.name}${sourceMultiplicity} *-- ${targetMultiplicity} ${target.name}${label}\n`
            break
          case RELATIONSHIP_TYPES.AGGREGATION:
            code += `${source.name}${sourceMultiplicity} o-- ${targetMultiplicity} ${target.name}${label}\n`
            break
          case RELATIONSHIP_TYPES.DEPENDENCY:
            code += `${source.name} ..> ${target.name}${label}\n`
            break
          case RELATIONSHIP_TYPES.ASSOCIATION:
            code += `${source.name}${sourceMultiplicity} --> ${targetMultiplicity} ${target.name}${label}\n`
            break
          case RELATIONSHIP_TYPES.BIDIRECTIONAL:
            code += `${source.name}${sourceMultiplicity} <--> ${targetMultiplicity} ${target.name}${label}\n`
            break
          case RELATIONSHIP_TYPES.REFLEXIVE:
            code += `${source.name} --> ${source.name}${label}\n`
            break
          default:
            code += `${source.name} -- ${target.name}${label}\n`
        }
      }
    }
  })

  return code
}

/**
 * 生成活动图代码
 * @param {Array} elements - 元素数组
 * @returns {string} 活动图代码
 */
function generateActivityDiagram(elements) {
  let code = ''

  const activityElements = elements.filter(el => el.type === ELEMENT_TYPES.ACTIVITY)
  const relationships = elements.filter(el => el.type === ELEMENT_TYPES.RELATIONSHIP && el.sourceId && el.targetId)
  const notes = elements.filter(el => el.type === ELEMENT_TYPES.NOTE)

  if (activityElements.length === 0) return code

  // 简单转义名称中的换行等
  const norm = (s) => (s || '').toString().replace(/\n/g, '\\n')

  // 收集分区
  const partitions = activityElements.filter(el => el.activityType === ACTIVITY_TYPES.PARTITION)
  const partitionMap = new Map() // 用于记录元素所属的分区

  // 为每个元素分配分区
  activityElements.forEach(element => {
    if (element.partitionId) {
      partitionMap.set(element.id, element.partitionId)
    }
  })

  // 收集决策点和合并点，用于后续处理条件分支
  const decisions = activityElements.filter(el => el.activityType === ACTIVITY_TYPES.DECISION)
  const merges = activityElements.filter(el => el.activityType === ACTIVITY_TYPES.MERGE)
  
  // 收集分叉和汇合点，用于并行处理
  const forks = activityElements.filter(el => el.activityType === ACTIVITY_TYPES.FORK)
  const joins = activityElements.filter(el => el.activityType === ACTIVITY_TYPES.JOIN)

  // 处理开始节点
  const startNodes = activityElements.filter(el => el.activityType === ACTIVITY_TYPES.START)
  if (startNodes.length > 0) {
    code += 'start\n'
  }

  // 处理分区
  partitions.forEach(partition => {
    const partitionElements = activityElements.filter(el => 
      partitionMap.get(el.id) === partition.id && 
      el.activityType !== ACTIVITY_TYPES.PARTITION
    )
    
    if (partitionElements.length > 0) {
      const partitionColor = partition.color ? `|#${partition.color}|` : ''
      code += `partition "${norm(partition.name)}" ${partitionColor} {\n`
      
      // 这里不直接输出分区内的元素，而是在后续的关系处理中处理
      
      code += '}\n'
    }
  })

  // 处理条件分支
  decisions.forEach(decision => {
    const outgoingRelations = relationships.filter(rel => rel.sourceId === decision.id)
    
    if (outgoingRelations.length > 0) {
      code += `:${norm(decision.name)};\n`
      code += 'if (条件判断?) then (是)\n'
      
      // 处理"是"分支
      const yesBranch = outgoingRelations.find(rel => 
        rel.name && ['yes', 'true', '是', '成功', '通过'].includes(rel.name.toLowerCase())
      ) || outgoingRelations[0]
      
      if (yesBranch) {
        const target = activityElements.find(el => el.id === yesBranch.targetId)
        if (target) {
          code += `  :${norm(target.name)};\n`
        }
      }
      
      // 处理"否"分支
      const noBranch = outgoingRelations.find(rel => 
        rel.name && ['no', 'false', '否', '失败', '不通过'].includes(rel.name.toLowerCase())
      ) || (outgoingRelations.length > 1 ? outgoingRelations[1] : null)
      
      if (noBranch) {
        code += 'else (否)\n'
        const target = activityElements.find(el => el.id === noBranch.targetId)
        if (target) {
          code += `  :${norm(target.name)};\n`
        }
      }
      
      code += 'endif\n'
    }
  })

  // 处理循环
  const repeatNodes = activityElements.filter(el => el.activityType === ACTIVITY_TYPES.REPEAT)
  repeatNodes.forEach(repeatNode => {
    code += `repeat\n`
    code += `  :${norm(repeatNode.name)};\n`
    
    // 查找循环条件
    const outgoingRelations = relationships.filter(rel => rel.sourceId === repeatNode.id)
    if (outgoingRelations.length > 0) {
      const conditionLabel = outgoingRelations[0].name || '条件'
      code += `repeat while (${conditionLabel}?) is (true)\n`
    } else {
      code += `repeat while (条件?) is (true)\n`
    }
  })

  // 处理并行
  forks.forEach(fork => {
    const outgoingRelations = relationships.filter(rel => rel.sourceId === fork.id)
    
    if (outgoingRelations.length > 0) {
      code += 'fork\n'
      
      outgoingRelations.forEach((rel, index) => {
        const target = activityElements.find(el => el.id === rel.targetId)
        if (target) {
          if (index > 0) {
            code += 'fork again\n'
          }
          code += `  :${norm(target.name)};\n`
        }
      })
      
      code += 'end fork\n'
    }
  })

  // 处理其他活动元素和关系
  // 我们使用一个已处理的关系集合来避免重复处理
  const processedRelations = new Set()
  
  // 处理未被特殊处理的关系
  relationships.forEach(rel => {
    // 如果关系已经被处理过，则跳过
    if (processedRelations.has(rel.id)) return
    
    const source = activityElements.find(el => el.id === rel.sourceId)
    const target = activityElements.find(el => el.id === rel.targetId)
    
    // 跳过已经在特殊结构中处理过的元素
    if (!source || !target) return
    if ([ACTIVITY_TYPES.DECISION, ACTIVITY_TYPES.FORK, ACTIVITY_TYPES.REPEAT].includes(source.activityType)) return

    // 源节点
    if (source.activityType === ACTIVITY_TYPES.START) {
      // 开始节点已经在前面处理过了
    } else if (source.activityType === ACTIVITY_TYPES.END) {
      code += 'stop\n'
    } else {
      code += `:${norm(source.name)};\n`
    }

    // 箭头和标签
    let arrow = '->'
    if (rel.relationshipType === RELATIONSHIP_TYPES.DEPENDENCY) {
      // 数据流使用橙色虚线
      arrow = '-[#orange,dashed]->'
      // 如果没有标签，为数据流添加默认标签
      const defaultLabel = '数据'
      const label = rel.name ? ` ${norm(rel.name)}` : ` ${defaultLabel}`
      code += `${arrow}${label}\n`
    } else {
      // 控制流使用蓝色实线
      arrow = '-[#blue]->'
    const label = rel.name ? ` ${norm(rel.name)}` : ''
    code += `${arrow}${label}\n`
    }

    // 目标节点
    if (target.activityType === ACTIVITY_TYPES.START) {
      // 不太可能有指向开始节点的关系
    } else if (target.activityType === ACTIVITY_TYPES.END) {
      code += 'stop\n'
    } else if (![ACTIVITY_TYPES.DECISION, ACTIVITY_TYPES.MERGE, ACTIVITY_TYPES.FORK, ACTIVITY_TYPES.JOIN].includes(target.activityType)) {
      // 对于非特殊节点，直接输出
      code += `:${norm(target.name)};\n`
    }
    
    // 标记关系为已处理
    processedRelations.add(rel.id)
  })

  // 处理注释
  notes.forEach(note => {
    if (note.targetId) {
      const target = activityElements.find(el => el.id === note.targetId)
      if (target) {
        code += `note ${note.position || 'right'} : ${norm(note.content)}\n`
      }
    } else {
      code += `note "${norm(note.content)}"\n`
    }
  })

  // 处理未连接的结束节点
  const endNodes = activityElements.filter(el => el.activityType === ACTIVITY_TYPES.END)
  const connectedEndNodes = new Set(
    relationships.filter(rel => {
      const target = activityElements.find(el => el.id === rel.targetId)
      return target && target.activityType === ACTIVITY_TYPES.END
    }).map(rel => rel.targetId)
  )
  
  endNodes.forEach(endNode => {
    if (!connectedEndNodes.has(endNode.id)) {
      code += 'stop\n'
    }
  })

  return code
}

/**
 * 生成时序图代码
 * @param {Array} elements - 元素数组
 * @returns {string} 时序图代码
 */
function generateSequenceDiagram(elements) {
  let code = ''
  
  // 启用精确布局
  code += '!pragma teoz true\n\n'
  
  // 自动编号
  code += 'autonumber "<b>[000]"\n\n'
  
  // 收集注释
  const notes = elements.filter(el => el.type === ELEMENT_TYPES.NOTE)
  
  // 定义参与者
  elements.forEach(element => {
    if (element.type === ELEMENT_TYPES.LIFELINE) {
      const elementName = element.name.replace(/\s+/g, '')
      const alias = elementName || `P${element.id}`
      
      switch (element.participantType) {
        case PARTICIPANT_TYPES.ACTOR:
          code += `actor "${element.name}" as ${alias}`
          break
        case PARTICIPANT_TYPES.DATABASE:
          code += `database "${element.name}" as ${alias}`
          break
        case PARTICIPANT_TYPES.BOUNDARY:
          code += `boundary "${element.name}" as ${alias}`
          break
        case PARTICIPANT_TYPES.CONTROL:
          code += `control "${element.name}" as ${alias}`
          break
        case PARTICIPANT_TYPES.ENTITY:
          code += `entity "${element.name}" as ${alias}`
          break
        case PARTICIPANT_TYPES.COLLECTIONS:
          code += `collections "${element.name}" as ${alias}`
          break
        case PARTICIPANT_TYPES.QUEUE:
          code += `queue "${element.name}" as ${alias}`
          break
        default:
          code += `participant "${element.name}" as ${alias}`
      }
      
      // 处理参与者颜色
      if (element.color) {
        code += ` #${element.color}`
      }
      
      code += '\n'
    }
  })

  code += '\n'

  // 处理分组
  const groups = new Map() // 用于记录消息所属的分组
  let currentGroup = null
  let groupStack = [] // 用于处理嵌套分组

  // 定义消息和交互
  const relationships = elements.filter(el => 
    el.type === ELEMENT_TYPES.RELATIONSHIP && el.sourceId && el.targetId
  )
  
  // 按照时间顺序排序关系
  relationships.sort((a, b) => (a.sequenceNumber || 0) - (b.sequenceNumber || 0))
  
  // 处理激活状态
  const activations = new Map() // 记录每个生命线的激活状态
  
  relationships.forEach(element => {
      const source = elements.find(el => el.id === element.sourceId)
      const target = elements.find(el => el.id === element.targetId)
      
    if (!source || !target) return
    
    const sourceName = source.name.replace(/\s+/g, '') || `P${source.id}`
    const targetName = target.name.replace(/\s+/g, '') || `P${target.id}`
    const messageLabel = element.name ? ` : ${element.name}` : ''
    
    // 处理分组开始
    if (element.groupStart) {
      if (element.groupType === 'alt') {
        code += 'alt 成功路径\n'
      } else if (element.groupType === 'loop') {
        const loopCount = element.loopCount || ''
        code += `loop ${loopCount}\n`
      } else if (element.groupType === 'opt') {
        code += 'opt 可选\n'
      } else if (element.groupType === 'par') {
        code += 'par 并行处理\n'
      } else {
        code += `group ${element.groupName || '分组'}\n`
      }
      
      groupStack.push(element.groupType)
    }
    
    // 处理分组中的分支
    if (element.groupBranch && groupStack.length > 0 && groupStack[groupStack.length - 1] === 'alt') {
      code += 'else 失败路径\n'
    }
    
    // 处理并行分支
    if (element.parallelBranch && groupStack.length > 0 && groupStack[groupStack.length - 1] === 'par') {
      code += 'and\n'
    }
    
    // 处理激活状态
    if (element.activateTarget && !activations.get(targetName)) {
      activations.set(targetName, true)
      code += `activate ${targetName}\n`
    }
    
    // 处理消息类型
        switch (element.relationshipType) {
          case RELATIONSHIP_TYPES.DEPENDENCY:
        // 返回消息
        code += `${targetName} --> ${sourceName}${messageLabel}\n`
        break
      case RELATIONSHIP_TYPES.ASYNC:
        // 异步消息
        code += `${sourceName} ->> ${targetName}${messageLabel}\n`
        break
      case RELATIONSHIP_TYPES.CREATE:
        // 创建消息
        code += `${sourceName} -> ${targetName}${messageLabel} : <<create>>\n`
        break
      case RELATIONSHIP_TYPES.DESTROY:
        // 销毁消息
        code += `${sourceName} -> ${targetName}${messageLabel} : <<destroy>>\n`
        code += `destroy ${targetName}\n`
            break
          case RELATIONSHIP_TYPES.ASSOCIATION:
          default:
        // 同步消息
        code += `${sourceName} -> ${targetName}${messageLabel}\n`
    }
    
    // 处理自动停用
    if (element.deactivateTarget && activations.get(targetName)) {
      activations.set(targetName, false)
      code += `deactivate ${targetName}\n`
    }
    
    // 处理分组结束
    if (element.groupEnd && groupStack.length > 0) {
      const groupType = groupStack.pop()
      if (groupType === 'loop') {
        code += 'end loop\n'
      } else if (groupType === 'alt') {
        code += 'end\n'
      } else if (groupType === 'opt') {
        code += 'end\n'
      } else if (groupType === 'par') {
        code += 'end\n'
      } else {
        code += 'end\n'
      }
    }
  })

  // 处理注释
  notes.forEach(note => {
    if (note.targetId) {
      const target = elements.find(el => el.id === note.targetId)
      if (target) {
        const targetName = target.name.replace(/\s+/g, '') || `P${target.id}`
        code += `note ${note.position || 'right'} of ${targetName} : ${note.content}\n`
      }
    } else {
      code += `note over ${note.position || ''} : ${note.content}\n`
    }
  })

  // 关闭所有未关闭的激活状态
  activations.forEach((isActive, participantName) => {
    if (isActive) {
      code += `deactivate ${participantName}\n`
    }
  })

  return code
}

/**
 * 生成用例图代码
 * @param {Array} elements - 元素数组
 * @returns {string} 用例图代码
 */
function generateUseCaseDiagram(elements) {
  let code = ''
  
  // 设置布局方向
  code += 'left to right direction\n\n'
  
  // 设置用例样式
  code += 'skinparam usecase {\n'
  code += '  BackgroundColor PaleGreen\n'
  code += '  BorderColor DarkSlateGray\n'
  code += '}\n\n'
  
  // 收集系统边界和云
  const systems = elements.filter(el => 
    el.type === ELEMENT_TYPES.USECASE && 
    (el.usecaseType === USECASE_TYPES.SYSTEM || el.usecaseType === USECASE_TYPES.RECTANGLE)
  )
  
  const clouds = elements.filter(el => 
    el.type === ELEMENT_TYPES.USECASE && 
    el.usecaseType === USECASE_TYPES.CLOUD
  )
  
  const packages = elements.filter(el => 
    el.type === ELEMENT_TYPES.USECASE && 
    el.usecaseType === USECASE_TYPES.PACKAGE
  )
  
  // 收集注释
  const notes = elements.filter(el => el.type === ELEMENT_TYPES.NOTE)
  
  // 定义参与者和用例
  const actors = elements.filter(el => 
    el.type === ELEMENT_TYPES.USECASE && 
    el.usecaseType === USECASE_TYPES.ACTOR
  )
  
  const usecases = elements.filter(el => 
    el.type === ELEMENT_TYPES.USECASE && 
    el.usecaseType === USECASE_TYPES.USECASE
  )
  
  // 处理参与者
  actors.forEach(actor => {
    // 处理参与者类型
    if (actor.stereotype) {
      code += `actor ${actor.name} << ${actor.stereotype} >>\n`
    } else {
      code += `actor ${actor.name}\n`
    }
    
    // 处理参与者颜色
    if (actor.color) {
      code += `skinparam actor${actor.name} {\n`
      code += `  BackgroundColor #${actor.color}\n`
      code += `}\n`
    }
  })
  
  // 处理用例
  usecases.forEach(usecase => {
    // 处理用例在系统边界内的情况
    if (usecase.systemId) {
      // 在后面的系统边界处理中会处理
    } else {
      // 处理用例类型
      if (usecase.stereotype) {
        code += `usecase "${usecase.name}" as ${usecase.id} << ${usecase.stereotype} >>\n`
      } else {
        code += `usecase "${usecase.name}" as ${usecase.id}\n`
      }
    }
  })
  
  // 处理系统边界
  systems.forEach(system => {
    code += `rectangle "${system.name}" {\n`
    
    // 处理系统内的用例
    const systemUsecases = usecases.filter(uc => uc.systemId === system.id)
    systemUsecases.forEach(usecase => {
      if (usecase.stereotype) {
        code += `  usecase "${usecase.name}" as ${usecase.id} << ${usecase.stereotype} >>\n`
      } else {
        code += `  usecase "${usecase.name}" as ${usecase.id}\n`
      }
    })
    
    code += '}\n\n'
  })
  
  // 处理云
  clouds.forEach(cloud => {
    code += `cloud "${cloud.name}" {\n`
    
    // 处理云内的用例
    const cloudUsecases = usecases.filter(uc => uc.cloudId === cloud.id)
    cloudUsecases.forEach(usecase => {
      code += `  usecase "${usecase.name}" as ${usecase.id}\n`
    })
    
    code += '}\n\n'
  })
  
  // 处理包
  packages.forEach(pkg => {
    code += `package "${pkg.name}" {\n`
    
    // 处理包内的用例
    const packageUsecases = usecases.filter(uc => uc.packageId === pkg.id)
    packageUsecases.forEach(usecase => {
      code += `  usecase "${usecase.name}" as ${usecase.id}\n`
    })
    
    code += '}\n\n'
  })

  // 定义关系
  elements.forEach(element => {
    if (element.type === ELEMENT_TYPES.RELATIONSHIP && element.sourceId && element.targetId) {
      const source = elements.find(el => el.id === element.sourceId)
      const target = elements.find(el => el.id === element.targetId)
      
      if (source && target) {
        // 处理关系标签
        const label = element.name ? ` : ${element.name}` : ''
        
        // 获取元素ID或名称
        const sourceId = source.id || source.name
        const targetId = target.id || target.name
        
        switch (element.relationshipType) {
          case RELATIONSHIP_TYPES.ASSOCIATION:
            code += `${sourceId} --> ${targetId}${label}\n`
            break
          case RELATIONSHIP_TYPES.INHERITANCE:
            code += `${sourceId} <|-- ${targetId}${label}\n`
            break
          case RELATIONSHIP_TYPES.DEPENDENCY:
            code += `${sourceId} ..> ${targetId} : <<include>>${label}\n`
            break
          case RELATIONSHIP_TYPES.REALIZATION:
            code += `${sourceId} ..> ${targetId} : <<extend>>${label}\n`
            break
          case RELATIONSHIP_TYPES.BIDIRECTIONAL:
            code += `${sourceId} <--> ${targetId}${label}\n`
            break
          default:
            code += `${sourceId} -- ${targetId}${label}\n`
        }
      }
    }
  })
  
  // 处理注释
  notes.forEach(note => {
    if (note.targetId) {
      const target = elements.find(el => el.id === note.targetId)
      if (target) {
        const targetId = target.id || target.name
        code += `note ${note.position || 'right'} of ${targetId}\n  ${note.content}\nend note\n`
      }
    } else {
      code += `note "${note.content}" as N${note.id}\n`
    }
  })

  return code
}

/**
 * 生成状态图代码
 * @param {Array} elements - 元素数组
 * @returns {string} 状态图代码
 */
function generateStateDiagram(elements) {
  let code = ''
  
  // 收集注释
  const notes = elements.filter(el => el.type === ELEMENT_TYPES.NOTE)
  
  // 收集状态
  const states = elements.filter(el => el.type === ELEMENT_TYPES.STATE)
  
  // 收集复合状态
  const compositeStates = states.filter(el => el.stateType === STATE_TYPES.COMPOSITE)
  
  // 创建状态ID映射
  const stateIdMap = new Map()
  states.forEach(state => {
    stateIdMap.set(state.id, state.name || `State_${state.id}`)
  })
  
  // 处理初始状态
  const initialStates = states.filter(el => el.stateType === STATE_TYPES.INITIAL)
  initialStates.forEach(state => {
    code += `[*] --> ${state.name || `State_${state.id}`}\n`
  })
  
  // 处理普通状态
  states.filter(el => el.stateType === STATE_TYPES.STATE).forEach(state => {
    // 处理状态描述
    if (state.description) {
      code += `state "${state.name}" as ${state.id} : ${state.description}\n`
    } else {
      code += `state "${state.name}" as ${state.id}\n`
    }
    
    // 处理状态颜色
    if (state.color) {
      code += `${state.id} : #${state.color}\n`
    }
  })
  
  // 处理复合状态
  compositeStates.forEach(state => {
    code += `state "${state.name}" as ${state.id} {\n`
    
    // 处理内部初始状态
    code += '  [*] --> InternalState1\n'
    
    // 处理子状态
    const childStates = states.filter(el => el.parentId === state.id)
    if (childStates.length > 0) {
      childStates.forEach(childState => {
        code += `  state "${childState.name}" as ${childState.id}\n`
      })
      
      // 处理子状态之间的转换
      elements.filter(el => 
        el.type === ELEMENT_TYPES.RELATIONSHIP && 
        childStates.some(cs => cs.id === el.sourceId) && 
        childStates.some(cs => cs.id === el.targetId)
      ).forEach(rel => {
        const source = states.find(el => el.id === rel.sourceId)
        const target = states.find(el => el.id === rel.targetId)
        
        if (source && target) {
          const transitionLabel = rel.name ? ` : ${rel.name}` : ''
          code += `  ${source.id} --> ${target.id}${transitionLabel}\n`
        }
      })
    } else {
      // 如果没有子状态，添加一些示例状态
      code += '  state InternalState1\n'
      code += '  state InternalState2\n'
      code += '  InternalState1 --> InternalState2\n'
      code += '  InternalState2 --> [*]\n'
    }
    
          code += '}\n'
  })
  
  // 处理选择状态
  states.filter(el => el.stateType === STATE_TYPES.CHOICE).forEach(state => {
    code += `state "${state.name}" as ${state.id} <<choice>>\n`
  })
  
  // 处理历史状态
  states.filter(el => el.stateType === STATE_TYPES.HISTORY).forEach(state => {
    code += `state "${state.name}" as ${state.id} <<history>>\n`
  })
  
  // 处理深度历史状态
  states.filter(el => el.stateType === STATE_TYPES.DEEP_HISTORY).forEach(state => {
    code += `state "${state.name}" as ${state.id} <<deepHistory>>\n`
  })
  
  // 处理分叉和合并状态
  states.filter(el => el.stateType === STATE_TYPES.FORK).forEach(state => {
    code += `state "${state.name}" as ${state.id} <<fork>>\n`
  })
  
  states.filter(el => el.stateType === STATE_TYPES.JOIN).forEach(state => {
    code += `state "${state.name}" as ${state.id} <<join>>\n`
  })
  
  // 处理最终状态
  const finalStates = states.filter(el => el.stateType === STATE_TYPES.FINAL)
  finalStates.forEach(state => {
    code += `state "${state.name}" as ${state.id} <<end>>\n`
    code += `${state.id} --> [*]\n`
  })
  
  // 处理内部活动
  states.forEach(state => {
    if (state.entryAction || state.exitAction || state.doAction) {
      code += `${state.id} : {\n`
      if (state.entryAction) {
        code += `  entry / ${state.entryAction}\n`
      }
      if (state.doAction) {
        code += `  do / ${state.doAction}\n`
      }
      if (state.exitAction) {
        code += `  exit / ${state.exitAction}\n`
      }
      code += '}\n'
    }
  })

  // 定义转换
  elements.forEach(element => {
    if (element.type === ELEMENT_TYPES.RELATIONSHIP && element.sourceId && element.targetId) {
      const source = states.find(el => el.id === element.sourceId)
      const target = states.find(el => el.id === element.targetId)
      
      // 跳过已经处理过的初始状态和最终状态的转换
      if (source && source.stateType === STATE_TYPES.INITIAL) return
      if (target && target.stateType === STATE_TYPES.FINAL) return
      
      if (source && target) {
        // 处理转换标签、条件和动作
        let transitionLabel = ''
        
        if (element.name) {
          transitionLabel += ` : ${element.name}`
        }
        
        if (element.condition) {
          transitionLabel += ` [${element.condition}]`
        }
        
        if (element.action) {
          transitionLabel += ` / ${element.action}`
        }
        
        code += `${source.id} --> ${target.id}${transitionLabel}\n`
      }
    }
  })
  
  // 处理注释
  notes.forEach(note => {
    if (note.targetId) {
      const target = states.find(el => el.id === note.targetId)
      if (target) {
        code += `note ${note.position || 'left'} of ${target.id}\n  ${note.content}\nend note\n`
      }
    } else {
      code += `note "${note.content}" as N${note.id}\n`
    }
  })

  return code
}


